07. Exercise: Recycling ViewHolders

L7 10 Implementing An Adapter SC

In this lesson, we'll explore how onBindViewHolder works when views get recycled.

  1. Update onBindViewHolder to show low sleep quality in red.

    Add an if block and set the sleep quality to red if sleepQuality is 1 or less:

    if (item.sleepQuality <= 1) {
      holder.textView.setTextColor(Color.RED) 
    } 


  2. Run your app again to see your RecyclerView Adapter in action:

    Add enough items that you can scroll up and down. Notice that rows that scroll back onto the screen are in red, regardless of their sleepQuality value. We’ll fix that now.


  3. Add an else block to reset the color:

    This will fix the bug we just introduced by making sure to always set the text color correctly, based on the value of sleepQuality.

    if (item.sleepQuality <= 1) {
       holder.textView.setTextColor(Color.RED) 
    } else {
       holder.textView.setTextColor(Color.BLACK) 
    }


  4. Run your app again to see your RecyclerView Adapter in action:

    You will see that the color is always set correctly now!

If you want to start at this step, you can download this exercise from: Step.03-Exercise-Recycling-ViewHolders.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.03-Solution-Recycling-ViewHolders, or using this git diff.

Task Description:

Complete these steps to update colors in onBindViewHolder() when view is recycled.

Task List:

Task Feedback:

Congrats! In the next exercise you'll dive into how ViewHolders work and implement your own!

Reference Documentation